import logging
from logging.handlers import RotatingFileHandler
from restfx import App
from restfx.http import FileResponse

import worker

# 配置日志记录
logger = logging.getLogger('app')
logger.setLevel(logging.INFO)

# 创建 RotatingFileHandler，限制日志文件大小为 10MB，最多保留 5 个备份文件
handler = RotatingFileHandler(
    'app.log',
    maxBytes=10 * 1024 * 1024,  # 10MB
    backupCount=5
)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

app = App('./', 'is-port-alive')

app.map_routes({
    'v1': 'apis'
})
app.map_static({
    '/': 'web'
})


def home_page(request):
    try:
        logger.info('Received request for home page')
        return FileResponse('./web/index.html')
    except Exception as e:
        logger.error(f'Error serving home page: {e}')
        # 这里可返回一个错误响应，假设 App 有相应方法
        return app.error_response(500, 'Internal Server Error')


app.map_urls({
    '/': home_page
})
app.collect()
app.persist()

# 检查间隔时长 60 秒
check_interval = 300

if __name__ == '__main__':
    from dist import routes_map

    try:
        logger.info(f'Starting worker with check interval {check_interval} seconds')
        worker.start(check_interval)
        logger.info('Worker started successfully')
    except Exception as e:
        logger.error(f'Failed to start worker: {e}')

    try:
        logger.info('Registering routes')
        app.register_routes(routes_map.routes)
        logger.info('Routes registered successfully')

        logger.info('Starting application')
        app.startup(host='172.16.53.2', port=81)
        logger.info('Application started successfully')
    except Exception as e:
        logger.error(f'Failed to start application: {e}')